// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package io.flutter.plugins.webviewflutter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;

import java.util.Map;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;

public final class WebViewFactory extends PlatformViewFactory implements PluginRegistry.ActivityResultListener {
    private final BinaryMessenger messenger;
    private final View containerView;
    private final Activity mActivity;
    private FlutterWebView flutterWebView;

    WebViewFactory(BinaryMessenger messenger, View containerView, Activity activity) {
        super(StandardMessageCodec.INSTANCE);
        this.messenger = messenger;
        this.containerView = containerView;
        this.mActivity = activity;
    }

    @SuppressWarnings("unchecked")
    @Override
    public PlatformView create(Context context, int id, Object args) {
        Map<String, Object> params = (Map<String, Object>) args;
        flutterWebView = new FlutterWebView(context, messenger, id, params, containerView, mActivity);
        return flutterWebView;
    }


    public void onPause() {
        if (null != flutterWebView && null != flutterWebView.webView) {
            flutterWebView.webView.onPause();
        }
    }

    public void onResume() {
        if (null != flutterWebView && null != flutterWebView.webView) {
            flutterWebView.webView.onResume();
        }
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1303) {
            flutterWebView.onActivityResult(requestCode, resultCode, data);
            return true;
        }
        return false;
    }
}
